<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="SKU名称">
        <el-input v-model="form.skuName" style="max-width: 50%"></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input
          type="number"
          v-model="form.price"
          style="max-width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量(kg)">
        <el-input v-model="form.weight" style="max-width: 50%"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
          v-model="form.skuDesc"
          type="textarea"
          style="max-width: 50%"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form-item
          v-for="(data, j) in AttrList"
          :key="j + '_' + data.id"
          :label="data.attrName"
        >
          <!-- 添加currentCheckedId标识,到时候通过currentCheckedId找到选择的值 -->
          <el-select v-model="data.currentCheckedId" placeholder="">
            <el-option
              v-for="(obj, i) in data.attrValueList"
              :key="obj.id + '_' + i"
              :label="obj.valueName"
              :value="obj.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="售卖属性">
        <el-form-item
          v-for="(data, i) in SaleAttrList"
          :key="data.id + '_' + i"
          :label="data.saleAttrName"
        >
          <!-- 添加currentCheckedId标识,到时候通过currentCheckedId找到选择的值 -->
          <el-select v-model="data.currentCheckedId">
            <el-option
              v-for="(obj, j) in data.spuSaleAttrValueList"
              :key="j + '_' + obj.id"
              :label="obj.saleAttrValueName"
              :value="obj.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="SKU图片">
        <el-table
          border
          :data="spuImgList"
          @selection-change="handleSelectionChange"
          ref="imgTableRef"
        >
          <el-table-column label="选择" type="selection" align="center">
          </el-table-column>
          <el-table-column label="图片">
            <template slot-scope="{ row }">
              <img
                style="width: 150px; height: 100px; object-fit: contain"
                :src="row.imgUrl"
              />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-tag
                v-if="row.isDefault && row.isDefault == 1"
                disable-transitions
                >默认图片</el-tag
              >
              <el-button
                v-else
                type="primary"
                size="mini"
                @click="setDefaultImg(row, spuImgList)"
                >设置默认图片</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 保存取消 -->
      <el-button type="primary" @click="saveInfo" :disabled="!form.skuName">
        保存</el-button
      >
      <el-button type="" @click="cancel"> 取消</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      skuId: '',
      SaleAttrList: [],
      AttrList: [],
      spuImgList: [],
      skuImgList_init: [],
      form: {
        category3Id: 0,
        spuId: 0,
        // 品牌ID
        tmId: 0,
        createTime: '2022-11-02T10:39:10.553Z',
        // sku id,添加时无id
        id: undefined,
        isSale: 1,
        skuName: '',
        skuDesc: '',
        weight: '',
        skuDefaultImg: '',
        price: 0,
        // sku平台属性
        skuAttrValueList: [
          // {
          //   attrId: 0,
          //   attrName: '',
          //   id: 0,
          //   skuId: undefined,
          //   valueId: 0,
          //   valueName: ''
          // }
        ],
        // sku售卖属性
        skuSaleAttrValueList: [
          // {
          //   id: 0,
          //   saleAttrId: 0,
          //   saleAttrName: '',
          //   saleAttrValueId: 0,
          //   saleAttrValueName: '',
          //   skuId: undefined,
          //   spuId: 0
          // }
        ],
        skuImageList: [
          // {
          //   id: undefined,
          //   imgName: '',
          //   imgUrl: '',
          //   isDefault: '',
          //   skuId: this.form.id,
          //   spuImgId: 0
          // }
        ]
      }
    }
  },
  methods: {
    // 设置默认图片
    setDefaultImg(row, list) {
      this.form.skuDefaultImg = row.imgUrl
      list.forEach((item) => {
        if (item == row) {
          item.isDefault = '1'
        } else {
          item.isDefault = '0'
        }
      })
    },
    // 添加勾选的图片
    handleSelectionChange(val) {
      this.skuImgList_init = val
      // this.form.skuImageList = val 不能这样写
    },
    // 提交
    async saveInfo() {
      const { spuId, form, AttrList, SaleAttrList } = this
      // 合法性判断
      if (form.skuName) {
        // 数据整理
        // <!-- 添加currentCheckedId标识,到时候通过currentCheckedId找到选择的值 -->
        //  添加选择的平台属性
        AttrList.forEach((item) => {
          let currentCheckedId = 0
          if (isNaN(item.currentCheckedId * 1)) {
            // 未修改
            currentCheckedId = item.currentCheckedId_init
          } else {
            // 已修改
            currentCheckedId = item.currentCheckedId
          }
          item.attrValueList.forEach((value) => {
            if (value.id == currentCheckedId) {
              form.skuAttrValueList.push({
                // 属性名
                attrId: item.id,
                attrName: item.attrName,
                // 该记录id
                id: undefined,
                // 属性值
                skuId: this.form.id,
                valueId: value.id,
                valueName: value.valueName
              })
            }
          })
        })
        // 添加选择的售卖属性
        SaleAttrList.forEach((item) => {
          let id = 0
          if (isNaN(item.currentCheckedId * 1)) {
            // 未修改
            id = item.currentCheckedId_init
          } else {
            // 已修改
            id = item.currentCheckedId
          }
          item.spuSaleAttrValueList.forEach((value) => {
            if (value.id == id) {
              form.skuSaleAttrValueList.push({
                // 该记录id 无
                id: undefined,
                // 属性名
                saleAttrId: item.id,
                saleAttrName: item.saleAttrName,
                // 属性值
                saleAttrValueId: value.id,
                saleAttrValueName: value.saleAttrValueName,
                skuId: this.form.id,
                spuId
              })
            }
          })
        })
        // 图片列表
        form.skuImageList = this.skuImgList_init
        const res = await this.$API.sku.updataSkuInfo(form)
        if (res.code == 200) {
          this.$message({ type: 'success', message: '修改SKU成功' })
          this.clearForm()
          this.emitchangeShow(true, 'edit')
        } else {
          this.$message({
            type: 'error',
            message: res.message + ':' + (res.data || '')
          })
        }
      } else {
        this.$message({ type: 'warning', message: '信息不完整' })
      }
    },
    cancel() {
      const { skuName, skuDesc, weight } = this.form
      if (skuName || skuDesc || weight) {
        this.$confirm('当前数据未保存是否仍要返回?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
          .then(() => {
            this.clearForm()
            this.emitchangeShow()
          })
          .catch(() => {})
      } else {
        this.emitchangeShow()
      }
    },
    // 切换显示
    emitchangeShow(is_update, flag) {
      this.$emit('changeShow', is_update, flag)
    },
    // 获spu对应的取售卖属性列表
    async getSaleAttrList(spuId) {
      const res = await this.$API.sku.getSaleAttrList(spuId)
      if (res.code == 200) {
        this.SaleAttrList = res.data
        // 实现select显示已选择属性值的名字
        this.form.skuSaleAttrValueList.forEach((item) => {
          for (let i = 0; i < this.SaleAttrList.length; i++) {
            let saleAttr = this.SaleAttrList[i]
            if (item.saleAttrId == saleAttr.baseSaleAttrId) {
              saleAttr.currentCheckedId = item.saleAttrValueName
              saleAttr.currentCheckedId_init = item.saleAttrValueId
              break
            }
          }
        })

        // 清空 form的skuAttrValueList skuDefaultImg skuSaleAttrValueList
        this.form.skuSaleAttrValueList = []
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    // 根据平台属性id(attrid)获取其对应的属性值列表
    async getAttrValueList(attrId) {
      const res = await this.$API.sku.getAttrValueList(attrId)
      if (res.code == 200) {
        return res.data
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
        return []
      }
    },
    // 获取spu图片列表
    async getSpuImageList(spuId) {
      const res = await this.$API.sku.getSpuImageList(spuId)
      if (res.code == 200) {
        res.data.forEach((item) => {
          if (!item.isDefault) {
            item['isDefault'] = '0'
          }
        })
        this.spuImgList = res.data

        // 将用户之前选择,设置的图片信息显示到页面上
        this.$nextTick(() => {
          this.form.skuImageList.forEach((item) => {
            for (let i = 0; i < this.spuImgList.length; i++) {
              let obj = this.spuImgList[i]
              if (item.imgUrl == obj.imgUrl) {
                obj.isDefault = item.isDefault

                // 显示为选中
                this.$refs.imgTableRef.toggleRowSelection(obj, true)
                break
              }
            }
          })

          // 清空 form的skuAttrValueList skuDefaultImg skuSaleAttrValueList
          this.form.skuImageList = []
        })
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    // 获取要编辑的sku信息
    async getSkuInfoById(id) {
      const res = await this.$API.sku.getSkuInfoById(id)
      if (res.code == 200) {
        this.form = res.data
        // 为平台属性添加属性值的列表(重难点)
        for (let i = 0; i < this.form.skuAttrValueList.length; i++) {
          let item = this.form.skuAttrValueList[i]
          const data = await this.getAttrValueList(item.attrId)
          this.AttrList.push({
            id: item.attrId,
            attrName: item.attrName,
            attrValueList: data,
            // 实现select显示已选择属性值的名字
            currentCheckedId: item.valueName,
            // 保存已选择属性值id
            currentCheckedId_init: item.valueId
          })
        }

        // 清空 form的skuAttrValueList skuDefaultImg skuSaleAttrValueList
        // 提交时会根据用户进行的修改进行添加
        this.form.skuAttrValueList = []
      } else {
        this.$message({
          type: 'error',
          message: res.message + ':' + (res.data || '')
        })
      }
    },
    async eidtSkuInfo({ spuId, id }) {
      this.skuId = id
      await this.getSkuInfoById(id) //首先获取(重要)
      await this.getSaleAttrList(spuId)
      await this.getSpuImageList(spuId)
      this.emitchangeShow(false, 'edit')
    },
    clearForm() {
      this.form = {
        category3Id: 0,
        spuId: 0,
        // 品牌ID
        tmId: 0,
        createTime: '2022-11-02T10:39:10.553Z',
        // sku id,添加时无id
        id: undefined,
        isSale: 1,
        skuName: '',
        skuDesc: '',
        weight: '',
        skuDefaultImg: '',
        price: 0,
        // sku平台属性
        skuAttrValueList: [],
        // sku售卖属性
        skuSaleAttrValueList: [],
        skuImageList: []
      }
    }
  },
  created() {
    this.$Bus.$on('editSkuInfo', this.eidtSkuInfo)
  }
}
</script>

<style></style>
